<!-- 登录页面 -->
<template>
  <view class="login-container">
    <!-- 顶部背景 -->
    <view class="login-header">
      <image class="login-bg" src="/static/images/login-bg.png" mode="aspectFill"></image>
      <view class="login-title">
        <image class="login-logo" :src="config.sitelogo || '/static/images/logo.png'" mode="aspectFit"></image>
        <text class="login-name">{{ config.sitename || 'CMS内容管理系统' }}</text>
      </view>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <u-tabs :list="tabList" :current="currentTab" @change="onTabChange"></u-tabs>
      
      <!-- 账号密码登录 -->
      <view class="login-form-item" v-if="currentTab === 0">
        <u-form :model="accountForm" ref="accountFormRef">
          <u-form-item prop="username">
            <u-input
              v-model="accountForm.username"
              placeholder="请输入用户名/手机号"
              prefixIcon="account"
              clearable
            ></u-input>
          </u-form-item>
          <u-form-item prop="password">
            <u-input
              v-model="accountForm.password"
              type="password"
              placeholder="请输入密码"
              prefixIcon="lock"
              clearable
              password
            ></u-input>
          </u-form-item>
          <u-form-item v-if="showCaptcha">
            <view class="captcha-box">
              <u-input
                v-model="accountForm.captcha"
                placeholder="请输入验证码"
                prefixIcon="checkbox-mark"
                clearable
                style="flex: 1;"
              ></u-input>
              <image class="captcha-img" :src="captchaUrl" @click="refreshCaptcha" mode="aspectFit"></image>
            </view>
          </u-form-item>
        </u-form>
        <view class="login-options">
          <view class="remember-box">
            <u-checkbox v-model="accountForm.remember" shape="circle">记住密码</u-checkbox>
          </view>
          <view class="forget-box" @click="goForgetPassword">
            <text>忘记密码?</text>
          </view>
        </view>
        <u-button type="primary" block @click="handleAccountLogin">登录</u-button>
      </view>
      
      <!-- 手机验证码登录 -->
      <view class="login-form-item" v-if="currentTab === 1">
        <u-form :model="mobileForm" ref="mobileFormRef">
          <u-form-item prop="mobile">
            <u-input
              v-model="mobileForm.mobile"
              placeholder="请输入手机号"
              prefixIcon="phone"
              clearable
            ></u-input>
          </u-form-item>
          <u-form-item prop="captcha">
            <view class="captcha-box">
              <u-input
                v-model="mobileForm.captcha"
                placeholder="请输入验证码"
                prefixIcon="checkbox-mark"
                clearable
                style="flex: 1;"
              ></u-input>
              <u-button 
                type="primary" 
                size="mini" 
                :disabled="smsSending" 
                @click="sendSmsCode"
              >{{ smsText }}</u-button>
            </view>
          </u-form-item>
        </u-form>
        <u-button type="primary" block @click="handleMobileLogin">登录</u-button>
      </view>
    </view>
    
    <!-- 第三方登录 -->
    <view class="third-login">
      <view class="third-title">
        <text class="line"></text>
        <text class="text">其他登录方式</text>
        <text class="line"></text>
      </view>
      <view class="third-icons">
        <view class="third-icon" @click="handleWechatLogin">
          <u-icon name="weixin-fill" color="#09bb07" size="60"></u-icon>
          <text>微信</text>
        </view>
        <view class="third-icon" @click="handleAppleLogin">
          <u-icon name="apple-fill" color="#333333" size="60"></u-icon>
          <text>Apple</text>
        </view>
      </view>
    </view>
    
    <!-- 注册入口 -->
    <view class="register-entry">
      <text>还没有账号？</text>
      <text class="register-link" @click="goRegister">立即注册</text>
    </view>
    
    <!-- 用户协议 -->
    <view class="agreement">
      <u-checkbox v-model="agreeProtocol" shape="circle">
        <text>登录即代表您已同意</text>
        <text class="protocol" @click="goProtocol('user')">《用户协议》</text>
        <text>和</text>
        <text class="protocol" @click="goProtocol('privacy')">《隐私政策》</text>
      </u-checkbox>
    </view>
  </view>
</template>

<script>
import { common, login } from '@/api/cms'

export default {
  data() {
    return {
      tabList: [
        { name: '账号密码登录' },
        { name: '手机验证码登录' }
      ],
      currentTab: 0,
      accountForm: {
        username: '',
        password: '',
        captcha: '',
        captchaId: '',
        remember: false
      },
      mobileForm: {
        mobile: '',
        captcha: ''
      },
      showCaptcha: false,
      captchaUrl: '',
      smsSending: false,
      smsText: '获取验证码',
      smsTimer: null,
      smsCountdown: 60,
      agreeProtocol: true,
      config: {}
    }
  },
  onLoad() {
    // 获取系统配置
    this.getConfig()
    
    // 检查是否需要显示验证码
    this.checkCaptcha()
    
    // 检查是否有记住的账号密码
    this.checkRememberAccount()
  },
  methods: {
    // 获取系统配置
    async getConfig() {
      try {
        const { data } = await common.getConfig()
        if (data.code === 1) {
          this.config = data.data.config || {}
        }
      } catch (error) {
        console.error('获取系统配置失败', error)
      }
    },
    
    // 切换登录方式
    onTabChange(index) {
      this.currentTab = index
    },
    
    // 检查是否需要显示验证码
    checkCaptcha() {
      // 这里可以根据后端配置或登录失败次数决定是否显示验证码
      this.showCaptcha = false
      
      // 如果需要显示验证码，则获取验证码
      if (this.showCaptcha) {
        this.refreshCaptcha()
      }
    },
    
    // 刷新验证码
    async refreshCaptcha() {
      try {
        const { data } = await common.getCaptcha()
        if (data.code === 1) {
          this.captchaUrl = data.data.captcha
          this.accountForm.captchaId = data.data.key
        }
      } catch (error) {
        console.error('获取验证码失败', error)
      }
    },
    
    // 发送短信验证码
    async sendSmsCode() {
      if (!this.mobileForm.mobile) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }
      
      // 验证手机号格式
      if (!/^1\d{10}$/.test(this.mobileForm.mobile)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }
      
      try {
        // 发送短信验证码
        // 这里应该调用发送短信验证码的接口
        // 为了演示，这里直接显示倒计时
        this.smsSending = true
        this.smsCountdown = 60
        this.smsText = `${this.smsCountdown}s`
        
        this.smsTimer = setInterval(() => {
          this.smsCountdown--
          this.smsText = `${this.smsCountdown}s`
          
          if (this.smsCountdown <= 0) {
            clearInterval(this.smsTimer)
            this.smsSending = false
            this.smsText = '获取验证码'
          }
        }, 1000)
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
      } catch (error) {
        console.error('发送短信验证码失败', error)
        uni.showToast({
          title: '发送验证码失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 账号密码登录
    async handleAccountLogin() {
      // 检查是否同意协议
      if (!this.agreeProtocol) {
        uni.showToast({
          title: '请先同意用户协议和隐私政策',
          icon: 'none'
        })
        return
      }
      
      // 表单验证
      if (!this.accountForm.username) {
        uni.showToast({
          title: '请输入用户名/手机号',
          icon: 'none'
        })
        return
      }
      
      if (!this.accountForm.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }
      
      if (this.showCaptcha && !this.accountForm.captcha) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '登录中...'
        })
        
        const params = {
          username: this.accountForm.username,
          password: this.accountForm.password
        }
        
        if (this.showCaptcha) {
          params.captcha = this.accountForm.captcha
          params.captcha_id = this.accountForm.captchaId
        }
        
        const { data } = await login.login(params)
        
        uni.hideLoading()
        
        if (data.code === 1) {
          // 登录成功
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          
          // 保存用户信息和token
          uni.setStorageSync('userInfo', data.data.userInfo)
          uni.setStorageSync('token', data.data.token)
          
          // 如果记住密码，保存账号密码
          if (this.accountForm.remember) {
            uni.setStorageSync('rememberedAccount', {
              username: this.accountForm.username,
              password: this.accountForm.password
            })
          } else {
            uni.removeStorageSync('rememberedAccount')
          }
          
          // 跳转到首页
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }, 1500)
        } else {
          // 登录失败
          uni.showToast({
            title: data.msg || '登录失败',
            icon: 'none'
          })
          
          // 如果需要验证码，刷新验证码
          if (this.showCaptcha) {
            this.refreshCaptcha()
          }
          
          // 如果连续失败多次，显示验证码
          if (!this.showCaptcha) {
            this.showCaptcha = true
            this.refreshCaptcha()
          }
        }
      } catch (error) {
        uni.hideLoading()
        console.error('登录失败', error)
        uni.showToast({
          title: '登录失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 手机验证码登录
    async handleMobileLogin() {
      // 检查是否同意协议
      if (!this.agreeProtocol) {
        uni.showToast({
          title: '请先同意用户协议和隐私政策',
          icon: 'none'
        })
        return
      }
      
      // 表单验证
      if (!this.mobileForm.mobile) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }
      
      if (!this.mobileForm.captcha) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '登录中...'
        })
        
        const params = {
          mobile: this.mobileForm.mobile,
          captcha: this.mobileForm.captcha
        }
        
        const { data } = await login.mobileLogin(params)
        
        uni.hideLoading()
        
        if (data.code === 1) {
          // 登录成功
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
          
          // 保存用户信息和token
          uni.setStorageSync('userInfo', data.data.userInfo)
          uni.setStorageSync('token', data.data.token)
          
          // 跳转到首页
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }, 1500)
        } else {
          // 登录失败
          uni.showToast({
            title: data.msg || '登录失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('登录失败', error)
        uni.showToast({
          title: '登录失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 微信登录
    handleWechatLogin() {
      // #ifdef MP-WEIXIN
      uni.showLoading({
        title: '登录中...'
      })
      
      uni.login({
        provider: 'weixin',
        success: async (loginRes) => {
          try {
            // 获取微信登录code
            const code = loginRes.code
            
            // 调用后端接口，使用code换取openid和session_key
            const { data } = await login.wxLogin({
              code: code
            })
            
            uni.hideLoading()
            
            if (data.code === 1) {
              // 登录成功
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
              
              // 保存用户信息和token
              uni.setStorageSync('userInfo', data.data.userInfo)
              uni.setStorageSync('token', data.data.token)
              
              // 跳转到首页
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }, 1500)
            } else {
              // 登录失败
              uni.showToast({
                title: data.msg || '登录失败',
                icon: 'none'
              })
            }
          } catch (error) {
            uni.hideLoading()
            console.error('微信登录失败', error)
            uni.showToast({
              title: '登录失败，请稍后再试',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          uni.hideLoading()
          console.error('微信登录失败', err)
          uni.showToast({
            title: '微信登录失败，请稍后再试',
            icon: 'none'
          })
        }
      })
      // #endif
      
      // #ifdef APP-PLUS
      uni.showLoading({
        title: '登录中...'
      })
      
      uni.login({
        provider: 'weixin',
        success: async (loginRes) => {
          try {
            // 获取微信登录code
            const code = loginRes.code
            
            // 调用后端接口，使用code换取openid和session_key
            const { data } = await login.appLogin({
              code: code,
              type: 'weixin'
            })
            
            uni.hideLoading()
            
            if (data.code === 1) {
              // 登录成功
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
              
              // 保存用户信息和token
              uni.setStorageSync('userInfo', data.data.userInfo)
              uni.setStorageSync('token', data.data.token)
              
              // 跳转到首页
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }, 1500)
            } else {
              // 登录失败
              uni.showToast({
                title: data.msg || '登录失败',
                icon: 'none'
              })
            }
          } catch (error) {
            uni.hideLoading()
            console.error('微信登录失败', error)
            uni.showToast({
              title: '登录失败，请稍后再试',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          uni.hideLoading()
          console.error('微信登录失败', err)
          uni.showToast({
            title: '微信登录失败，请稍后再试',
            icon: 'none'
          })
        }
      })
      // #endif
      
      // #ifdef H5
      uni.showToast({
        title: 'H5环境暂不支持微信登录',
        icon: 'none'
      })
      // #endif
    },
    
    // 苹果登录
    handleAppleLogin() {
      // #ifdef APP-PLUS
      uni.showLoading({
        title: '登录中...'
      })
      
      uni.login({
        provider: 'apple',
        success: async (loginRes) => {
          try {
            // 获取苹果登录信息
            const { data } = await login.appLogin({
              code: loginRes.code,
              type: 'apple',
              user: loginRes.user
            })
            
            uni.hideLoading()
            
            if (data.code === 1) {
              // 登录成功
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
              
              // 保存用户信息和token
              uni.setStorageSync('userInfo', data.data.userInfo)
              uni.setStorageSync('token', data.data.token)
              
              // 跳转到首页
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }, 1500)
            } else {
              // 登录失败
              uni.showToast({
                title: data.msg || '登录失败',
                icon: 'none'
              })
            }
          } catch (error) {
            uni.hideLoading()
            console.error('苹果登录失败', error)
            uni.showToast({
              title: '登录失败，请稍后再试',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          uni.hideLoading()
          console.error('苹果登录失败', err)
          uni.showToast({
            title: '苹果登录失败，请稍后再试',
            icon: 'none'
          })
        }
      })
      // #endif
      
      // #ifndef APP-PLUS
      uni.showToast({
        title: '当前环境暂不支持苹果登录',
        icon: 'none'
      })
      // #endif
    },
    
    // 检查是否有记住的账号密码
    checkRememberAccount() {
      const rememberedAccount = uni.getStorageSync('rememberedAccount')
      if (rememberedAccount) {
        this.accountForm.username = rememberedAccount.username
        this.accountForm.password = rememberedAccount.password
        this.accountForm.remember = true
      }
    },
    
    // 跳转到忘记密码页面
    goForgetPassword() {
      uni.navigateTo({
        url: '/pages/login/forget'
      })
    },
    
    // 跳转到注册页面
    goRegister() {
      uni.navigateTo({
        url: '/pages/login/register'
      })
    },
    
    // 跳转到协议页面
    goProtocol(type) {
      uni.navigateTo({
        url: `/pages_article/page/index?type=${type}`
      })
    }
  },
  onUnload() {
    // 清除定时器
    if (this.smsTimer) {
      clearInterval(this.smsTimer)
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding-bottom: 50rpx;
}

.login-header {
  position: relative;
  height: 400rpx;
  overflow: hidden;
}

.login-bg {
  width: 100%;
  height: 100%;
}

.login-title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-logo {
  width: 160rpx;
  height: 160rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.login-name {
  font-size: 36rpx;
  color: #ffffff;
  font-weight: bold;
}

.login-form {
  margin: -50rpx 40rpx 0;
  padding: 40rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.login-form-item {
  margin-top: 30rpx;
}

.captcha-box {
  display: flex;
  align-items: center;
}

.captcha-img {
  width: 200rpx;
  height: 80rpx;
  margin-left: 20rpx;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20rpx 0 40rpx;
}

.forget-box {
  font-size: 28rpx;
  color: #999999;
}

.third-login {
  margin: 80rpx 40rpx 0;
}

.third-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.line {
  width: 100rpx;
  height: 1rpx;
  background-color: #eeeeee;
}

.text {
  margin: 0 20rpx;
  font-size: 28rpx;
  color: #999999;
}

.third-icons {
  display: flex;
  justify-content: center;
}

.third-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 40rpx;
  
  text {
    margin-top: 10rpx;
    font-size: 24rpx;
    color: #666666;
  }
}

.register-entry {
  margin-top: 60rpx;
  text-align: center;
  font-size: 28rpx;
  color: #666666;
}

.register-link {
  color: #2979ff;
  margin-left: 10rpx;
}

.agreement {
  margin: 40rpx 0 0;
  text-align: center;
  font-size: 24rpx;
  color: #999999;
}

.protocol {
  color: #2979ff;
}
</style>